package com.five.sso.controller;

import com.five.core.result.Result;
import com.five.core.result.ResultEnum;
import com.five.sso.dto.MsgLoginDto;
import com.five.sso.dto.RegisterDto;
import com.five.sso.service.UserService;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/register")
    public Result register(@RequestBody @Validated RegisterDto registerDto, BindingResult bindingResult){
        Result errors = errorMsg(bindingResult);

        if (errors != null){
            return errors;
        }
        return userService.register(registerDto)>0?Result.buildSuccess(ResultEnum.ADD_TRUE):Result.buildFail(ResultEnum.ADD_FALSE);
    }

    @PostMapping("/login/")
    public Result login(@RequestBody @Validated MsgLoginDto msgLoginDto, BindingResult bindingResult, @RequestHeader("User-Agent") String userAgent){
        Result errors = errorMsg(bindingResult);
        if (errors != null){
            return errors;
        }
        String token = userService.loginByPhone(msgLoginDto,userAgent);
        return token==null ? Result.buildFail(ResultEnum.LOGIN_ERROR) : Result.buildSuccess(token);
    }

    @PostMapping("/oneLogin")
    public Result oneLoginByPhone(@RequestBody @Validated MsgLoginDto msgLoginDto, BindingResult bindingResult,@RequestHeader("User-Agent") String userAgent){
        Result errors = errorMsg(bindingResult);
        if (errors!=null){
            return errors;
        }
        String token = userService.oneLoginByPhone(msgLoginDto,userAgent);
        return token==null ? Result.buildFail(ResultEnum.LOGIN_ERROR) : Result.buildSuccess(token);
    }

    @PostMapping("/loginOut")
    public Result loginOut(@RequestHeader("Authorization") String token,@RequestHeader("User-Agent") String userAgent){
        System.out.println("token = " + token);
        int i = userService.loginOut(token, userAgent);
        return i>0 ? Result.buildSuccess() : Result.buildFail(ResultEnum.OPTION_FAIL);
    }

    private Result errorMsg(BindingResult bindingResult) {
        if (bindingResult.hasErrors()){
            Map<String, String> errors = new HashMap<>();
            bindingResult.getFieldErrors().forEach(fieldError -> {
                String field = fieldError.getField();
                String message = fieldError.getDefaultMessage();
                errors.put(field, message);
            });
            return Result.buildFieldError(errors);
        }
        return null;
    }
}
